<template>
  <basicModal @register="modalRegister" ref="modalRef">
    <template #default>
      <a-form
        :model="formParams"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="mt-6"
      >
        <a-form-item label="导入步骤">
          <a-typography-text type="secondary">
            请先下载模板，按约定格式填写文章内容，从下面选择模板导入
          </a-typography-text>
        </a-form-item>

        <a-form-item label="下载模板">
          <a-button type="text" @click="downloadTemp"> 下载模板 </a-button>
        </a-form-item>

        <a-form-item label="文章模板">
          <a-upload
            :action="`${uploadUrl}${urlPrefix}/article/import`"
            :headers="uploadHeaders"
            :show-file-list="false"
            :show-retry-button="false"
            accept=".xls,.xlsx"
            @finish="importChange"
          >
            <a-button type="primary" :loading="importBtn">
              <template #icon>
                <ImportOutlined />
              </template>
              选择模板
            </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </template>
    <template #action></template>
  </basicModal>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { Notification, Message } from '@arco-design/web-vue';
  import type { formParamsType } from './types';
  import { basicModal, useModal } from '@/components/Modal';
  import { useGlobSetting } from '@/hooks/setting';
  import { useUserStore } from '@/store/modules/user';
  import { ImportOutlined } from '@vicons/antd';

  const globSetting = useGlobSetting();

  const { uploadUrl, urlPrefix } = globSetting;
  const userStore = useUserStore();

  const importBtn = ref(false);

  const emit = defineEmits(['change', 'register']);

  const props = defineProps({
    title: {
      type: String,
      default: '导入文章',
    },
    width: {
      type: Number,
      default: 450,
    },
  });

  const formRef: any = ref(null);
  const token = userStore.getToken;

  const [modalRegister, { openModal, closeModal }] = useModal({
    title: props.title,
    subBtuText: '保存',
    width: 550,
    showAction: false,
  });

  const defaultValueRef = () => ({
    id: null,
    content: '',
    title: '',
    publicTime: null,
  });

  const formParams = ref<formParamsType>(defaultValueRef());

  const uploadHeaders = reactive({
    satoken: token,
  });

  // 下载模板
  function downloadTemp() {
    const downFile = document.createElement('a');
    downFile.style.display = 'none';
    downFile.href = '/xlsx/article.xls';
    downFile.download = 'article.xls'; // 下载后文件名
    document.body.appendChild(downFile);
    downFile.click();
    document.body.removeChild(downFile); // 下载完成移除元素
  }

  function importChange({ event }: { file; event?: any }) {
    if (event && event.target) {
      try {
        const res = eval('(' + event.target.response + ')');
        const { code, data, msg } = res;
        //成功
        if (code === 200) {
          let type = data.isSuc ? 'success' : 'error';
          Notification[type]({
            content: `导入总数：${data.totalCount}条，成功 ${data.sucCount}条，失败 ${data.failCount}条`,
            meta: data.isSuc ? '导入成功' : '导入失败',
          });
          emit('change');
          closeModal();
        } else Message.error(msg);
      } catch (error) {
        console.error(error);
      }
    }
  }

  async function showModal() {
    openModal();
  }

  defineExpose({
    showModal,
    closeModal,
  });
</script>

<style lang="less" scoped></style>
